﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace BlazorAdmin.Tcp.Server
{
    /// <summary>
    /// TCP服务扩展类
    /// </summary>
    public static class Extensions
    {
        /// <summary>
        /// 添加TCP服务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="options">Tcp服务参数</param>
        /// <returns></returns>
        public static IServiceCollection AddTcpService<T>(this IServiceCollection services, Func<TcpOptions>? options = null) where T : TcpToken, new()
        {
            TcpOptions? tcpOptions = null;
            if (null != options)
                tcpOptions = options.Invoke();
            tcpOptions ??= new TcpOptions();
            services.AddSingleton(tcpOptions);
            return services.AddSingleton<TcpServer<T>>();
        }

        /// <summary>
        /// 使用TCP服务
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="host"></param>
        /// <returns></returns>
        public static IHost UseTcpService<T>(this IHost host) where T : TcpToken, new()
        {
            if (host.Services.GetRequiredService<TcpServer<T>>() is not TcpServer<T> tcpServer)
                return host;
            tcpServer.Start();
            return host;
        }
    }
}
